﻿using CRMG.Container.Resources.ExceptionResources;
using CRMG.Container.Source.BO;
using CRMG.Container.Source.Helper;
using CRMG.Container.Source.OpManager;
using CRMG.Container.Source.Variables;
using Guru.ErrorHandling;
using Guru.Framework.Util;
using Guru.TransactionLogger;
using Guru.TransactionLogger.Source.BO;
using System;
using System.Globalization;
using System.IO;
using System.Resources;
using System.Threading;
using System.Windows.Forms;
using Telerik.WinControls.UI;

namespace CRMG.Container.Views.Studnt
{
    public partial class FrmStudent : RadForm
    {
        ResourceManager formRes;
        ResourceManager messageRes;
        LookupManager lookupMan;
        StudentManager stdntMan;
        Student student;
        int _studentId = -1;

        public FrmStudent()
            : this(-1)
        { }
        public FrmStudent(int studentId)
        {
            try
            {
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(AppVariables.ApplicationCulture);
                InitializeComponent();
                formRes = new ResourceManager("CRMG.Container.Resources.ControlResources.WinFormStrings", typeof(CRMGContainer).Assembly);
                messageRes = new ResourceManager("CRMG.Container.Resources.MessageResources.AppMessages", typeof(CRMGContainer).Assembly);
                this.Text = formRes.GetString("FrmStudent.Caption");
                _studentId = studentId;
                lookupMan = new LookupManager();
                stdntMan = new StudentManager();
                grpInfo.Text = formRes.GetString("FrmStudent.grpInfo");
                grpEdu.Text = formRes.GetString("FrmStudent.grpEdu");
                grpJob.Text = formRes.GetString("FrmStudent.grpJob");

                lblName.Text = formRes.GetString("FrmStudent.lblName");
                lblLastname.Text = formRes.GetString("FrmStudent.lblLastname");
                lblIdentity.Text = formRes.GetString("FrmStudent.lblIdentity");
                lblPhone.Text = formRes.GetString("FrmStudent.lblPhone");
                lblMobilePhone.Text = formRes.GetString("FrmStudent.lblMobilePhone");

                lblEmail.Text = formRes.GetString("FrmStudent.lblEmail");
                lblPassword.Text = formRes.GetString("FrmStudent.lblPassword");
                lblPassAgain.Text = formRes.GetString("FrmStudent.lblPassAgain");
                lblBirthDate.Text = formRes.GetString("FrmStudent.lblBirthDate");

                lblAddress.Text = formRes.GetString("FrmStudent.lblAddress");
                lblEduStatus.Text = formRes.GetString("FrmStudent.lblEduStatus");
                lblSchool.Text = formRes.GetString("FrmStudent.lblSchool");
                lblInst.Text = formRes.GetString("FrmStudent.lblInst");

                lblWorkStatus.Text = formRes.GetString("FrmStudent.lblWorkStatus");
                lblCompany.Text = formRes.GetString("FrmStudent.lblCompany");
                lblPosition.Text = formRes.GetString("FrmStudent.lblPosition");

                lblWorkPhone.Text = formRes.GetString("FrmStudent.lblWorkPhone");
                lblWorkMail.Text = formRes.GetString("FrmStudent.lblWorkMail");
                lblWorkAddress.Text = formRes.GetString("FrmStudent.lblWorkAddress");
                lblUserCreationDate.Text = formRes.GetString("FrmStudent.lblUserCreationDate");

                btnAddImage.Text = formRes.GetString("FrmStudent.btnAddImage");

                btnSave.Text = studentId == -1 ? formRes.GetString("Add") : formRes.GetString("Update");
            }
            catch (Exception exc)
            {
                LogEntry logger = new LogEntry(AppVariables.CurrentUser.OBJID)
                {
                    ErrorCode = 2005,
                    Message = exc.Message,
                    StackTrace = exc.StackTrace,
                    Title = Rc.GetString(2005)
                };
                logger.Write();
                ControlUtil.ShowErrorMessage(
                    messageRes.GetString("FrmStudent.Ctor.Error"),
                    messageRes.GetString("Error"));
            }
            finally
            {
                student = new Student();
            }
        }

        private void FormLoad(object sender, EventArgs e)
        {
            try
            {
                ControlUtil.LoadDataTable2DropDownList(drpCompany, lookupMan.GetCompanies(), "CompanyName", "OBJID");
                ControlUtil.LoadDataTable2DropDownList(drpPosition, lookupMan.GetPositions(), "PositionName", "OBJID");
                ControlUtil.LoadDataTable2DropDownList(drpSchool, lookupMan.GetSchools(), "SchoolName", "OBJID");
                ControlUtil.LoadDataTable2DropDownList(drpInst, lookupMan.GetDepartments(), "InstituteName", "OBJID");
                ControlUtil.LoadDataTable2DropDownList(drpEduStatus, lookupMan.GetGrades(), "GradeName", "OBJID");
                ControlUtil.LoadStringToDropDownList(drpJobStatus, formRes.GetString("FrmStudent.WorkState"), '-');

                if (_studentId != -1)
                {
                    student = stdntMan.GetStudentById(_studentId);
                    txtAddress.Text = student.Address;
                    dtpBirthDate.Value = student.BirthDate;
                    drpCompany.SelectedValue = student.CompanyId;
                    drpInst.SelectedValue = student.Department;
                    txtEmail.Text = student.EMail;
                    txtName.Text = student.FirstName;
                    drpEduStatus.SelectedValue = student.GradeId;
                    txtIdentity.Text = student.IdentityNo;
                    txtLastName.Text = student.LastName;
                    txtMobile.Text = student.MobilePhone;
                    txtPhone.Text = student.Phone;
                    drpPosition.SelectedValue = student.Position;
                    drpSchool.SelectedValue = student.School;
                    txtWorkAddress.Text = student.WorkAdress;
                    txtWorkEmail.Text = student.WorkEMail;
                    txtWorkPhone.Text = student.WorkPhone;
                    drpJobStatus.SelectedIndex = student.WorkState;
                    dtpUserCreationDate.Value = student.UserCreationDate;
                }
            }
            catch (Exception exc)
            {
                btnSave.Enabled = false;
                LogEntry logger = new LogEntry(AppVariables.CurrentUser.OBJID)
                {
                    ErrorCode = 2006,
                    Message = exc.Message,
                    StackTrace = exc.StackTrace,
                    Title = Rc.GetString(2006)
                };
                logger.Write();
                ControlUtil.ShowErrorMessage(
                    messageRes.GetString("FrmStudent.Load.Error"),
                    messageRes.GetString("Error"));
            }
            finally
            {
                student = new Student();
                if (_studentId == -1)
                {
                    student.IsActive = 1;
                    student.UserTypeId = 4;
                }
                else
                {
                    student.OBJID = _studentId;
                }
            }
        }

        private void FirstNameTextChange(object sender, EventArgs e)
        {
            student.FirstName = txtName.Text;
            //btnSave.Enabled = (txtName.Text.Length * txtLastName.Text.Length) > 0;
        }

        private void LastNameChange(object sender, EventArgs e)
        {
            student.LastName = txtLastName.Text;
            //btnSave.Enabled = (txtName.Text.Length * txtLastName.Text.Length) > 0;
        }

        private void IdentityNoChange(object sender, EventArgs e)
        {
            student.IdentityNo = txtIdentity.Text;
        }

        private void PhoneChange(object sender, EventArgs e)
        {
            student.Phone = txtPhone.Text;
        }

        private void MobilePhoneChange(object sender, EventArgs e)
        {
            student.MobilePhone = txtMobile.Text;
        }

        private void EMailChange(object sender, EventArgs e)
        {
            student.EMail = txtEmail.Text;
        }

        private void PassChange(object sender, EventArgs e)
        {
            student.Pass = txtPassword.Text;
        }

        private void AdressChange(object sender, EventArgs e)
        {
            student.Address = txtAddress.Text;
        }

        private void WorkPhoneChange(object sender, EventArgs e)
        {
            student.WorkPhone = txtWorkPhone.Text;
        }

        private void WorkMailChange(object sender, EventArgs e)
        {
            student.WorkEMail = txtEmail.Text;
        }

        private void WorkPhone(object sender, EventArgs e)
        {
            student.WorkPhone = txtWorkPhone.Text;
        }

        private void WorkAdressChange(object sender, EventArgs e)
        {
            student.WorkAdress = txtWorkAddress.Text;
        }

        private void GradeChange(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e)
        {
            student.GradeId = ConverterUtil.Convert2Int(drpEduStatus.SelectedValue);
        }

        private void SchoolChange(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e)
        {
            student.School = ConverterUtil.Convert2Int(drpSchool.SelectedValue);
        }

        private void DepartmentChange(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e)
        {
            student.Department = ConverterUtil.Convert2Int(drpInst.SelectedValue);
        }

        private void JobStatusChange(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e)
        {
            student.WorkState = drpJobStatus.SelectedIndex;
        }

        private void CompanyChange(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e)
        {
            student.CompanyId = ConverterUtil.Convert2Int(drpCompany.SelectedValue);
        }

        private void PositionChange(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e)
        {
            student.Position = ConverterUtil.Convert2Int(drpPosition.SelectedValue);
        }

        private void Save(object sender, EventArgs e)
        {
            try
            {
                if (txtName.Text.Length == 0)
                {
                    ControlUtil.ShowInfoMessage(
                        messageRes.GetString("FrmStudent.Save.EmptyName"),
                        messageRes.GetString("Info"));
                    return;
                }

                if (txtLastName.Text.Length == 0)
                {
                    ControlUtil.ShowInfoMessage(
                        messageRes.GetString("FrmStudent.Save.EmptyLastName"),
                        messageRes.GetString("Info"));
                    return;
                }
                if (stdntMan.IsStudentExist(student.FirstName, student.LastName) == true)
                {
                    System.Windows.Forms.DialogResult diaRes = ControlUtil.ShowConfirmDialog(
                                    messageRes.GetString("FrmStudentList.Save.StudentExist"),
                                    messageRes.GetString("Confirm"));
                    if (diaRes == System.Windows.Forms.DialogResult.No)
                    {
                        return;
                    }
                }
                if (txtEmail.Text.Length == 0)
                {
                    ControlUtil.ShowInfoMessage(
                        messageRes.GetString("FrmStudent.Save.EmptyEmail"),
                        messageRes.GetString("Info"));
                    return;
                }

                if (StringUtil.IsValidEMail(txtEmail.Text) == false)
                {
                    ControlUtil.ShowInfoMessage(
                        messageRes.GetString("FrmStudent.Save.InvalidEmail"),
                        messageRes.GetString("Info"));
                    return;
                }
                if (_studentId == -1)
                {
                    if (txtPassword.Text.Length == 0 || txtPassAgain.Text.Length == 0)
                    {
                        ControlUtil.ShowInfoMessage(
                            messageRes.GetString("FrmStudent.Save.EmptyPassword"),
                            messageRes.GetString("Info"));
                        return;
                    }

                    if (txtPassword.Text.Equals(txtPassAgain.Text) == false)
                    {
                        ControlUtil.ShowInfoMessage(
                            messageRes.GetString("FrmStudent.Save.NotEqualPasswords"),
                            messageRes.GetString("Info"));
                        return;
                    }
                }
                else
                {
                    if (txtPassword.Text.Equals(txtPassAgain.Text) == false)
                    {
                        ControlUtil.ShowInfoMessage(
                            messageRes.GetString("FrmStudent.Save.NotEqualPasswords"),
                            messageRes.GetString("Info"));
                        return;
                    }
                }

                if (txtPhone.Text.Length == 0)
                {
                    ControlUtil.ShowInfoMessage(
                        messageRes.GetString("FrmStudent.Save.EmptyPhone"),
                        messageRes.GetString("Info"));
                    return;
                }

                if (txtWorkEmail.Text.Length > 0)
                {
                    if (StringUtil.IsValidEMail(txtWorkEmail.Text) == false)
                    {
                        ControlUtil.ShowInfoMessage(
                       messageRes.GetString("FrmStudent.Save.InvalidWorkEmail"),
                       messageRes.GetString("Info"));
                        return;
                    }
                }

                if (_studentId == -1)
                {
                    student.UserCreationDate = dtpUserCreationDate.Value;
                    student.CreatedByUser = AppVariables.CurrentUser.OBJID;
                    int stdntId = stdntMan.AddStudent(student);
                    TransactionLogEntry transLogger = new TransactionLogEntry(AppVariables.CurrentUser.OBJID)
                    {
                        FormName = this.Name,
                        TransactionType = TransactionTypes.Insert,
                        ControlName = btnSave.Text,
                        ControlTag = btnSave.Tag != null ? btnSave.Tag.ToString() : "",
                        LogObject = stdntId
                    };
                    transLogger.Insert();
                    ResetControls();
                }
                else
                {
                    if (student.GetColumnChangeList().Count > 1)
                    {
                        student.UpdateTime = DateTime.Now;
                        student.UpdateUser = AppVariables.CurrentUser.OBJID;
                        stdntMan.UpdateStudent(student);
                        TransactionLogEntry transLogger = new TransactionLogEntry(AppVariables.CurrentUser.OBJID)
                        {
                            FormName = this.Name,
                            TransactionType = TransactionTypes.Update,
                            ControlName = btnSave.Text,
                            ControlTag = btnSave.Tag != null ? btnSave.Tag.ToString() : "",
                            LogObject = _studentId
                        };
                        transLogger.Insert();
                    }
                }

                btnSave.Enabled = false;
                btnCancel.Text = formRes.GetString("Close");
                ControlUtil.ShowInfoMessage(
                    messageRes.GetString("FrmStudent.Save.Success"),
                    messageRes.GetString("Info"));

            }
            catch (GuruException)
            {
                ControlUtil.ShowErrorMessage(
                       messageRes.GetString("FrmStudent.Save.Error"),
                       messageRes.GetString("Error"));
            }
            catch (Exception exc)
            {
                LogEntry logger = new LogEntry(AppVariables.CurrentUser.OBJID)
                {
                    ErrorCode = 2008,
                    Message = exc.Message,
                    StackTrace = exc.StackTrace,
                    Title = Rc.GetString(2008)
                };
                logger.Write();
                ControlUtil.ShowErrorMessage(
                    messageRes.GetString("FrmStudent.Save.Error"),
                    messageRes.GetString("Error"));
            }
        }


        private void Cancel(object sender, EventArgs e)
        {
            this.Close();
        }

        private void ResetControls()
        {
            ControlUtil.SetTextOfTextBoxes(string.Empty,
                txtEmail, txtLastName, txtName, txtPassAgain, txtPassword, txtWorkEmail);
            txtAddress.Text = string.Empty;
            txtIdentity.Text = string.Empty;
            txtIdentity.Text = string.Empty;
            txtMobile.Text = string.Empty;
            txtPhone.Text = string.Empty;
            txtWorkAddress.Text = string.Empty;
            txtWorkPhone.Text = string.Empty;
            drpCompany.SelectedIndex = -1;
            drpEduStatus.SelectedIndex = -1;
            drpInst.SelectedIndex = -1;
            drpJobStatus.SelectedIndex = -1;
            drpPosition.SelectedIndex = -1;
            drpSchool.SelectedIndex = -1;
            dtpBirthDate.Value = DateTime.Now;
            student = new Student() { IsActive = 1, UserTypeId = 4 };
        }

        private void btnAddImage_Click(object sender, EventArgs e)
        {
            try
            {
                using (OpenFileDialog ofd = new OpenFileDialog())
                {
                    ofd.Title = formRes.GetString("FrmStudent.OpenFileDialog.Title");
                    ofd.Filter = formRes.GetString("FrmStudent.OpenFileDialog.Filter");
                    ofd.Multiselect = false;
                    if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        student.Resim = File.ReadAllBytes(ofd.FileName);
                    }
                }
            }
            catch (Exception ex)
            {
                LogEntry logger = new LogEntry(AppVariables.CurrentUser.OBJID)
                {
                    ErrorCode = 2104,
                    Message = ex.Message,
                    StackTrace = ex.StackTrace,
                    Title = Rc.GetString(2104)
                };
                logger.Write();
                ControlUtil.ShowErrorMessage(
                    messageRes.GetString("FrmStudent.btnAddImage_Click.Error"),
                    messageRes.GetString("Error"));
            }
        }
    }
}
